package com.china.zhuoyue.ui.widget

import android.app.Activity
import android.content.Context
import android.os.Build
import android.util.AttributeSet
import android.webkit.*
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
import com.china.zhuoyue.ui.R
import com.china.zhuoyue.ui.dialog.showAlertDialog
import com.china.zhuoyue.ui.ext.getString

typealias TitleCangerListener = (title: String) -> Unit

class X5Webview : WebView, DefaultLifecycleObserver {
    var titleCangerListener: TitleCangerListener? = null

    constructor(context: Context) : this(context, null)

    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
        init(attrs)
    }

    private fun init(attrs: AttributeSet?) {
        (context as? LifecycleOwner)?.lifecycle?.addObserver(this)
//        if ( Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
//            setWebContentsDebuggingEnabled(true)
//        }
        settings.apply {
            javaScriptEnabled = true
            domStorageEnabled = true
            cacheMode = WebSettings.LOAD_NO_CACHE
            setAppCacheMaxSize(1024 * 1024 * 8.toLong())
            val appCachePath: String = context.cacheDir.absolutePath
            setAppCachePath(appCachePath)
            allowFileAccess = true
            setAppCacheEnabled(true)
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW
            }
        }
        webViewClient = object : WebViewClient() {
            override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
                view.loadUrl(url)
                return true
            }

            override fun onPageFinished(webView: WebView, url: String?) {
                titleCangerListener?.invoke(webView.title ?: R.string.app_name.getString())
            }
        }
        webChromeClient = object : WebChromeClient() {
            override fun onJsAlert(view: WebView?, url: String?, message: String?, result: JsResult?): Boolean {
                (context as? Activity)?.apply {
                    showAlertDialog {
                        message(message = message ?: "")
                        positiveButton { result?.confirm() }
                    }
                }
                return true
            }
        }
    }

    override fun onDestroy(owner: LifecycleOwner) {
        (context as? LifecycleOwner)?.lifecycle?.removeObserver(this)
        destroy()
    }
}